/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nms.base.crm;

import com.nms.base.ObjectPool;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author mohamedemara
 */
public class EntityManagerPool extends ObjectPool<EntityManager> {

    private static final String PRESISTANCE_UNIT_NAME = "CRMServicePU";
    private EntityManager em;
    private EntityManagerFactory emf;

    public EntityManagerPool() {
        try {
            emf = Persistence.createEntityManagerFactory(PRESISTANCE_UNIT_NAME);
        } catch (Exception ex) {
            System.out.println("Error On presistance unit");
            ex.printStackTrace();
        }
    }

    @Override
    protected EntityManager create() {
        EntityManager entityManager=null;
        try
        {
        entityManager= emf.createEntityManager();
        }
        catch(Exception ex)
        {
            System.out.println("Error While creating Entity Manager");
            ex.printStackTrace();
        }
        return entityManager;
    }

    @Override
    public boolean validate(EntityManager obj) {
        boolean result=false;
        try {
           result= obj.isOpen();
        } catch (Exception ex) {
            System.out.println("Error On Validate  pool Method");
            ex.printStackTrace();
        }
        return result;
    }

    @Override
    public void expire(EntityManager obj) {
        try {
            obj.close();
        } catch (Exception ex) {
            System.out.println("Error On closing Entity Manager");
            ex.printStackTrace();
        }
    }
}
